//
//  HWTimer.m
//  OCDemo
//
//  Created by 李含文 on 2021/5/10.
//

#import "HWTimer.h"

@interface HWTimer ()
{
    NSTimer *_timer;
}

@property (nonatomic, copy) void(^block)(void);

@property (nonatomic, weak) id target;
/// 是否是自动管理
@property (nonatomic, assign) BOOL isAuto;
@end

@implementation HWTimer

- (void)startTimerWithInterval:(NSTimeInterval)interval
                        target:(id)target
                        action:(void(^)(void))action {
    _isAuto = target?YES:NO;
    _target = target;
    self.block = action;
    //创建Timer
    _timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(work) userInfo:nil repeats:YES];
    //使用NSRunLoopCommonModes模式，把timer加入到当前Run Loop中。
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

- (void)work {
    if (_isAuto && !self.target) [self stopTimer]; // 如果target 不存在
    if (self.block) self.block();
}

- (void)stopTimer {
    if (_timer == nil) return;
    [_timer invalidate];
    _timer = nil;
}

- (void)dealloc {
    NSLog(@"定时器释放");
    [self stopTimer];
}
@end
